import KBEDebug as log
import KBEngine
import time
import math
import Utils


class ILobbySeasonRank:

    def __init__(self):
        self.season_ranks = {}
        self.season_rank_lst = []

        cur_time = int(time.time())
        self.load_time = cur_time
        if self.seasonRankStartTime <= 0:
            self.seasonRankStartTime = cur_time
        else:
            if Utils.isCrossMonth(self.seasonRankStartTime):
                # 清除排行数据
                self.clearRankInfo()
            else:
                self.loadAllRankInfo()

    def seasonMonthCheck(self):
        if Utils.isCrossMonth(self.seasonRankStartTime):
            # 清除排行数据
            self.clearRankInfo()

    def clearRankInfo(self):
        self.seasonRankStartTime = int(time.time())

        def callback(result, rows, insertid, error):
            if error:
                log.ERROR_MSG(f'clearRankInfo failed: {error}')
            else:
                self.loadAllRankInfo()
        sql = 'update lobby_group set totalCatchCount=0;'
        KBEngine.executeRawDatabaseCommand(sql, callback)

    def loadAllRankInfo(self, entity_call = None, getInfo = False):
        self.season_ranks.clear()
        self.season_rank_lst.clear()

        def callback(result, rows, insertid, error):
            if error:
                log.ERROR_MSG(f'loadAllRankInfo failed: {error}')
            else:
                log.DEBUG_MSG(f'loadAllRankInfo success {len(result)}')
                result_lst = []
                for line in result:
                    group_id = int(line[0])
                    group_name = str(line[1], 'utf-8')
                    group_memeber_count = int(line[2])
                    group_catch_cout = int(line[3])
                    item = {
                        'groupId': group_id,
                        'groupName': group_name,
                        'groupMemberCount': group_memeber_count,
                        'totalCatchCount': group_catch_cout
                    }
                    self.season_ranks[group_id] = item
                    result_lst.append(item)
                self.season_rank_lst = result_lst
                self.load_time = int(time.time())
                if getInfo is True and entity_call is not None:
                    total_count = len(self.season_rank_lst)
                    slice_num = 10
                    slice_count = math.ceil(total_count / slice_num)
                    if total_count == 0:
                        entity_call.client.repNoGroup()
                    else:
                        for i in range(slice_count):
                            start = i * slice_num
                            end = start + slice_num
                            entity_call.client.repSeasonRank(self.season_rank_lst[start:end], i, total_count)
                    
                    log.DEBUG_MSG(f'season rank clice_count:{slice_count}, total_count:{total_count}')
                    log.DEBUG_MSG('获取排行榜结束')

        sql = 'select groupId, groupName, groupMemberCount, totalCatchCount from lobby_group ORDER BY totalCatchCount DESC limit 100;'
        KBEngine.executeRawDatabaseCommand(sql, callback)

    def reqSeasonRank(self, entity_call):
        # 十分钟刷新一次排行榜
        if int(time.time()) - self.load_time >= 600:
            self.loadAllRankInfo(entity_call = entity_call, getInfo = True)
        else:
            total_count = len(self.season_rank_lst)
            slice_num = 10
            slice_count = math.ceil(total_count / slice_num)
            if total_count == 0:
                entity_call.client.repNoGroup()
            else:
                for i in range(slice_count):
                    start = i * slice_num
                    end = start + slice_num
                    entity_call.client.repSeasonRank(self.season_rank_lst[start:end], i, total_count)
            
            log.DEBUG_MSG(f'season rank clice_count:{slice_count}, total_count:{total_count}')
            log.DEBUG_MSG('获取排行榜结束')
